package com.tfd.blog.controller;

import com.tfd.blog.domain.Category;
import com.tfd.blog.domain.CategoryNode;
import com.tfd.blog.filter.NeedLogin;
import com.tfd.blog.repository.CategoryRepository;
import com.tfd.blog.utlis.JsonResult;
import com.tfd.blog.utlis.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataAccessException;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author TangFD
 * @since 2019/5/7.
 */
@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {

    @Resource
    private CategoryRepository categoryRepository;

    @NeedLogin
    @PostMapping("/manage/save")
    public JsonResult createOrUpdateCategory(@RequestBody Category paramCategory) {
        Category category;
        Date date = new Date();
        if (StringUtils.isEmpty(paramCategory.getId())) {
            category = paramCategory;
            category.setCreateDate(date);
        } else {
            category = categoryRepository.getOne(paramCategory.getId());
            category.setName(paramCategory.getName());
            category.setCode(paramCategory.getCode());
            category.setParentId(paramCategory.getParentId());
        }

        category.setUpdateDate(date);
        try {
            categoryRepository.save(category);
        } catch (DataAccessException e) {
            return new JsonResult("name or code duplicate", false);
        }
        return new JsonResult();
    }

    @NeedLogin
    @RequestMapping("/manage/del/{categoryId}")
    public JsonResult delCategoryById(@PathVariable(value = "categoryId") String categoryId) {
        categoryRepository.deleteById(categoryId);
        return new JsonResult();
    }

    @GetMapping("/get/{categoryId}")
    public JsonResult<Category> getCategoryById(String categoryId) {
        Category category = categoryRepository.getOne(categoryId);
        return new JsonResult<>("查询成功", category, true);
    }

    @NeedLogin
    @GetMapping("/manage/page")
    public JsonResult<Page<Category>> categoryByIds(Page<Category> page, String categoryName) {
        //jpa的分页是从0开始分页的下次需要注意
        PageRequest pageRequest = PageRequest.of(page.getPageNum() - 1, page.getPageSize());
        String name = "%" + categoryName + "%";
        org.springframework.data.domain.Page<Category> categoryPage = categoryRepository.pageByName(name, pageRequest);
        List<Category> content = categoryPage.getContent();
        page.setTotal(categoryPage.getTotalElements());
        page.setList(content);
        return new JsonResult<>("查询成功", page, true);
    }

    @NeedLogin
    @GetMapping("/findAll")
    public JsonResult<List<Category>> findAll() {
        List<Category> categoryList = categoryRepository.findAll(new Sort(Sort.Direction.DESC, "createDate"));
        return new JsonResult<>("查询成功", categoryList, true);
    }

    @NeedLogin
    @GetMapping("/getCategoryTree")
    public JsonResult<List<CategoryNode>> getCategoryTree() {
        CategoryNode allNode = new CategoryNode();
        allNode.setId("*");
        allNode.setName("全部");
        List<Category> categoryList = categoryRepository.findAll(new Sort(Sort.Direction.DESC, "createDate"));
        if (CollectionUtils.isEmpty(categoryList)) {
            return new JsonResult<>("查询成功", Collections.singletonList(allNode), true);
        }

        Map<String, CategoryNode> categoryNodeIdMap = getCategoryNodeIdMap(categoryList, allNode);
        for (Category category : categoryList) {
            String parentId = category.getParentId();
            CategoryNode node = categoryNodeIdMap.get(parentId);
            if (node == null) {
                continue;
            }

            List<CategoryNode> children = node.getChildren();
            children.add(categoryNodeIdMap.get(category.getId()));
        }

        return new JsonResult<>("查询成功", Collections.singletonList(allNode), true);
    }

    private Map<String, CategoryNode> getCategoryNodeIdMap(List<Category> categoryList, CategoryNode allNode) {
        Map<String, CategoryNode> categoryNodeIdMap = new HashMap<>(categoryList.size() + 1);
        for (Category category : categoryList) {
            String id = category.getId();
            categoryNodeIdMap.put(id, convertNode(category));
        }

        categoryNodeIdMap.put(allNode.getId(), allNode);
        return categoryNodeIdMap;
    }

    private CategoryNode convertNode(Category category) {
        CategoryNode node = new CategoryNode();
        node.setId(category.getId());
        node.setName(category.getName());
        node.setCode(category.getCode());
        node.setParentId(category.getParentId());
        return node;
    }
}
